<template>
  <div class="ChildPage TablePage" v-loading="loading">
    <vb-page ref="page" @onTableSelection="doSelect">
      <template #headerBtn="scope">
        <el-button size="small" type="success"  icon="el-icon-share" @click="updateStatus(this.selection)">关闭改审核</el-button>
        <el-button size="small" icon="el-icon-plus" type="primary" @click="updateBusinessStatus(this.selection)">完工改开工</el-button>
        <el-button size="small" icon="el-icon-plus" type="warning" @click="auditTaskByOneClick(this.selection)">一键审核</el-button>
      </template>

      <template #headerSearch-append="scope">
        <span style="font-size: 12px; padding-right: 10px; color: #666666">物料</span>
        <el-select filterable remote :remote-method="e => getMaterialList(e)" v-model="scope.searchForm.materialNo" size="small" clearable class="material" placeholder="请输入物料编码或者名称" style="margin-right: 10px; width: 23%">
          <el-option v-for="item in materialList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName + ' ' + item.fSpecification" :value="item.fNumber" />
        </el-select>
      </template>
      <template #table-handle-prepend="scope">
        <el-button size="mini" type="text" icon="el-icon-edit" style="color: #E6A23C" @click="gotoDetail(scope.row.billNo)">查看</el-button>
        <el-button size="mini" type="text" icon="el-icon-edit" v-if="hasPagePowerKey('apply') && scope.row.status === 'save'" @click.once="doAudit(scope.row.billNo)">审核</el-button>
        <el-button size="mini" type="text" icon="el-icon-delete" style="color: #F56C6C" v-if="hasPagePowerKey('delete') && (scope.row.businessStatus === 'create' || scope.row.businessStatus === 'release')" @click="doDelete(scope.row.billNo)">删除</el-button>
        <el-button size="mini" type="text" style="color:var(--el-color-success)" icon="el-icon-share" @click="toExport(scope.row.billNo)">导出</el-button>
        <el-button size="mini" type="text" icon="el-icon-upload2" style="color: #E6A23C" @click="goPDA(scope.row.billNo)">PDA</el-button>
        <el-button size="mini" type="text" icon="el-icon-s-promotion" style="color: #66CCFF" @click="syncKingdeeBn(scope.row)">金蝶</el-button>
      </template>
      <template #table-pickStatus="scope">
        <el-tag :type="scope.row.pickStatus? 'success': 'info'">{{ scope.row.pickStatus? '已领料': '未领料' }}</el-tag>
      </template>
      <template #table-isPrint="scope">
        <el-tag :type="scope.row.isPrint? 'success': 'info'">{{ scope.row.isPrint? '已打印': '未打印' }}</el-tag>
      </template>
      <template #table-status="scope">
        <el-tag :type="scope.row.status === 'save'? 'info': (scope.row.status === 'audit'? 'success': 'danger')">{{ scope.row.status === 'save'? '保存': (scope.row.status === 'audit'? '审核': '关闭') }}</el-tag>
      </template>
      <template #table-isUpload="scope">
        <el-tag :type="scope && scope.row && scope.row.isUpload === true? 'success': 'info'">{{scope && scope.row && scope.row.isUpload === true? '已上传': '未上传'}}</el-tag>
      </template>
      <template #footerBtn="data">
        已选行数:{{ selectionLength}},重量:{{selectCount}}
        <!--        <el-button type="primary" @click="doOpen" icon="el-icon-s-home" size="mini">选择行入库</el-button>-->
        <el-button type="primary" @click="doSelectClose" icon="el-icon-s-home" size="mini">选择行关闭</el-button>
      </template>
      <template #headerSearch-btn-append="{ searchForm }">
        <el-button type="warning" size="small" icon="el-icon-download" @click="doDownload(searchForm)">导出生产任务</el-button>
      </template>
    </vb-page>
  </div>
</template>

<script>
import syncKingdeeTime from "../components/syncKingdeeTimeDialogBn.vue";


export default {
  data() {
    return {
      materialLoading: false,
      reloadMaterial: false,
      selection: null,
      selectionLength:0,
      selectCount:0,
      materialList: [],
      username:''
    }
  },
  components: {
    syncKingdeeTime
  },
  async mounted() {
    await this.getStock()
    await this.getUserName()
  },
  methods: {
    async doDownload(searchForm) {
      this.loading = true
      try {
        let res = await this.callApi('download_prd_task_list_bn', searchForm)
        if (!res.res) return
      } finally {
        this.loading = false
      }
    },
    //获取当前登录用户名
    async getUserName(){
      try {
        let res = await this.callApi('get_userName')
        if (res.res){
          this.username = res.userName
          console.log(this.username)
        }
      } finally {
        this.loading = false
      }
    },
    //一键审核
    async auditTaskByOneClick(){
      if (!this.selection || this.selection.length === 0) {
        this.$message.error('没有选择行')
        return
      }
      //判断状态必须都是保存状态
      let statusRes = this.selection.every(function (item){
        return item.status === 'save'
      })
      if (!statusRes){
        this.$message.warning('存在已审核的单据')
      }
      let billNoList = []
      this.selection.forEach(function (item){
        billNoList.push(item.billNo);
      })
      this.loading = true
      try {
        let res = await this.callApi('audit_prd_task_bill_list', { billNoList: billNoList })
        if (!res.res) {
          return
        }
        this.$refs.page.reload()
        this.$message.success('审核完成!')
      } finally {
        this.loading = false
      }
    },
    //完工改开工
    async updateBusinessStatus(){
      if (!this.selection || this.selection.length === 0) {
        this.$message.error('没有选择行')
        return
      }
      let billNoList = []
      for(let i = 0; i < this.selection.length; i++) {
        if (this.selection[i].businessStatus === 'end'){
          billNoList.push(this.selection[i].billNo)
        } else {
          this.$message.error('只允许修改已完工的')
        }

      }
      try {
        await this.$confirm(`确定修改状态吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('update_prd_businessStatus', { billNoList: billNoList })
        if (!res.res) {
          return
        }
        this.$message.success(`修改完成!`)
        this.$refs.page.reload()
      } finally {
        this.loading = false
      }
    },
    //关闭改审核
    async updateStatus(){
      if (!this.selection || this.selection.length === 0) {
        this.$message.error('没有选择行')
        return
      }
      let billNoList = []
      for(let i = 0; i < this.selection.length; i++) {
          billNoList.push(this.selection[i].billNo)
      }
      try {
        await this.$confirm(`确定修改状态吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('update_prd_type', { billNoList: billNoList })
        if (!res.res) {
          return
        }
        this.$message.success(`修改完成!`)
        this.$refs.page.reload()
      } finally {
        this.loading = false
      }
    },
    //上传金蝶，选择时间
    async syncKingdeeBn(e){
      window.open(import.meta.env.VITE_EXPORT_URL + `syncKingdeeTimeDialogBn?billNo=${e.billNo}&type=${e.type}&createTime=${e.createTime}`)
    },
    async getMaterialList(val) {
      if (!val) {
        this.materialList = []
        return
      }
      this.materialLoading = true
      try {
        const res = await this.callApi('get_material_by_key', { key: val, pageSize: 20 })
        if (!res.res) return
        this.materialList = res.data
      } finally {
        this.materialLoading = false
      }
    },
    toExport(billNo) {
      // console.log(import.meta.env.VITE_EXPORT_URL)
      window.open(import.meta.env.VITE_EXPORT_URL + `taskExport?billNo=${ billNo}`)
    },
    async doSelectClose() {
      if (!this.selection || this.selection.length === 0) {
        this.$message.error('没有选择行')
        return
      }
      let billNoList = []
      for(let i = 0; i < this.selection.length; i++) {
        billNoList.push(this.selection[i].billNo)
      }
      try {
        await this.$confirm(`确定关闭单据吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('close_prd_order', { billNoList: billNoList })
        if (!res.res) {
          return
        }
        this.$message.success(`批量关闭完成!`)
        this.$refs.page.reload()
      } finally {
        this.loading = false
      }
    },
    doSelect(data) {
      this.selection = data
      this.selectionLength = this.selection.length;
      this.selectCount=0
      for (var i=0;i<this.selectionLength;i++){
        this.selectCount+=data[i].count
      }

    },
    async getStock() {
      this.loading = true;
      try {
        let res = await this.$api.getChildDictionaryListByKeys({
          keys: ['stock']
        });
        if (!res.res) return;
        this.stockList = res.stock;
      } finally {
        this.loading = false;
      }
    },
    /**
     * 获取状态名
     */
    getStockName(val) {
      if (this.stockList && this.stockList.length > 0) {
        for(let i = 0; i < this.stockList.length; i++) {
          if (this.stockList[i].key === val) {
            return this.stockList[i].name;
          }
        }
      }
      return '';
    },
    goPDA(billNo = ''){
      let url = '/produce/prdColPDA'
      if (billNo){
        url += `?billNo=${ billNo }`
      }
      this.$router.push(url)
    },
    gotoDetail(billNo = '') {
      let url = '/produce/produceTaskDetailBn'
      if (billNo) {
        url += `?billNo=${ billNo }`
      }
      this.$router.push(url)
    },
    async doAudit(billNo) {
      this.loading = true
      try {
        let res = await this.callApi('audit_prd_task_bill', { billNo: billNo })
        if (!res.res) {
          return
        }
        this.$refs.page.reload()
        this.$message.success('审核完成!')
      } finally {
        this.loading = false
      }
    },
    async doDelete(billNo) {
      this.loading = true
      try {
        let res = await this.callApi('delete_prd_task_bill', { billNo: billNo })
        if (!res.res) {
          return
        }
        this.$refs.page.reload()
        this.$message.success('删除成功!')
      } finally {
        this.loading = false
      }
    },
  }
}
</script>

<style scoped>

</style>
